package com.mt.api.core.config.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.mt.api.modules.domain.dto.AppBossDto;
import com.mt.api.modules.domain.dto.JwtUserDto;
import com.mt.api.util.JwtUserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * @Author: plover
 * @Date: 2021-11-02
 * @Description: mybatis-plus通用字段填充handler
 */
@Component
@Slf4j
public class FillMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        JwtUserDto jwtUser = JwtUserUtils.getJwtUser();
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
        if (Objects.nonNull(jwtUser)) {
            AppBossDto appBoss = jwtUser.getAppBoss();
            this.strictInsertFill(metaObject, "createId", Integer.class, appBoss.getId());
            this.strictInsertFill(metaObject, "creator", String.class, appBoss.getName());
            this.strictInsertFill(metaObject, "updateId", Integer.class, appBoss.getId());
            this.strictInsertFill(metaObject, "updater", String.class, appBoss.getName());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        JwtUserDto jwtUser = JwtUserUtils.getJwtUser();
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
        if (Objects.nonNull(jwtUser)) {
            AppBossDto appBoss = jwtUser.getAppBoss();
            this.strictInsertFill(metaObject, "updateId", Integer.class, appBoss.getId());
            this.strictInsertFill(metaObject, "updater", String.class, appBoss.getName());
        }
    }
}
